package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 单次任务限时（callWithTimeout）
 *
 * 适合无需代理，仅对单个任务（Callable/Runnable）设置超时的场景。
 *
 * @author yangyunjiao
 */
public class SingleTaskTimeoutDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        TimeLimiter timeLimiter = SimpleTimeLimiter.create(executor);

        try {
            // 执行 Callable 任务（有返回值），超时 2 秒
            String result = timeLimiter.callWithTimeout(
                    () -> { // 任务逻辑
                        Thread.sleep(3000); // 模拟 3 秒耗时
                        return "任务完成";
                    },
                    2,
                    TimeUnit.SECONDS
            );
            System.out.println(result);
        } catch (TimeoutException e) {
            System.err.println("任务超时：" + e.getMessage());
        } catch (Exception e) {
            System.err.println("任务执行异常：" + e.getMessage());
        } finally {
            executor.shutdown();
        }
    }
}
